import React, { useRef, useEffect, useContext, memo } from 'react';
import PropTypes from 'prop-types';
import getCssPrefix from '@root/lib/getCssPrefix';
import TableContext from '@root/lib/TableContext';
import BaseContent from './BaseContent';
import useGenStyle from './hooks/useGenStyle';

const { cssPrefix } = getCssPrefix();
const scrollId = 'baseTable';
function BaseTable(props) {
    const { sourceData, columns, width, align = 'center' } = props;
    const wrapperRef = useRef(null);
    const midRef = useRef(null);
    const ignoreScrollRef = useRef(null);
    const { key, rowsVisual, modifyRowsVisual, tableState, scrollUtility } = useContext(TableContext);
    let { wrapperStyle, midWrapperStyle } = useGenStyle(
        width, rowsVisual, sourceData.length,
        align, tableState
    );
    /* 同步scroll事件和对外分发scroll滚动信息（scroll发生在本组件时） */
    useEffect(() => {
        if (align === 'center' && midRef.current) {
            /* 注册scroll的关联 */
            scrollUtility.register(scrollId, function (v) {
                ignoreScrollRef.current = true;
                midRef.current.scrollLeft = v;
            });
            /* 添加dom的scroll事件 */
            midRef.current.addEventListener('scroll', (e) => {
                let ignore = ignoreScrollRef.current;
                ignoreScrollRef.current = false;
                if (ignore) return;
                typeof scrollUtility.scroll === 'function' && scrollUtility.scroll(scrollId, e.target.scrollLeft);
            })
        }
    }, []);
    return (
        <div className={`${cssPrefix}-base-table-wrapper`} style={wrapperStyle} ref={wrapperRef}>
            <div className={`${cssPrefix}-base-table-mid-wrapper`} style={midWrapperStyle} ref={midRef}>
                <BaseContent
                    data={sourceData}
                    rowsVisual={rowsVisual}
                    rowKey={key}
                    columns={columns}
                    modifyRowsVisual={modifyRowsVisual}
                    align={align}
                    width={width}
                />
            </div>
        </div>

    );
}
BaseTable.propTypes = {
    sourceData: PropTypes.array,
    columns: PropTypes.array,
}
export default memo(function Wrapper(props) {
    const { columns } = props;
    if (!columns?.length) {
        return null;
    }
    return <BaseTable {...props} />;
});
